package com.itheima.tilas.exception;

import com.itheima.tilas.Utils.ResultUtil;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

/**
 * 因为我们无法使用 try-catch捕获进入controller 之前的异常,但是我们可以使用AOP对controller进行调用之前的增强
 * 因此@RestControllerAdvice相当于环绕通知controller
 *
 * @author 132
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultUtil handleArithmeticException(ArithmeticException e) {
        return ResultUtil.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultUtil handleDefaultMessageSourceResolvable(MethodArgumentNotValidException e){
//        String defaultMessage = e.getFieldError().getDefaultMessage();
//        Object rejectedValue = e.getFieldError().getRejectedValue();
//        return ResultUtil.fail(defaultMessage,rejectedValue);
        //获取全部异常信息
        BindingResult result = e.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();
        StringJoiner joiner = new StringJoiner(",", "{", "}");
        for (FieldError error : errors) {
            joiner.add(error.getDefaultMessage());
        }
        return ResultUtil.fail(joiner.toString());
    }
}
